package com.javabi.common.text.parser;

import java.util.Collection;

public abstract class StringCollectionParser<L extends Collection<String>> extends ObjectParser<L> {

	private char delimiter = ',';

	public void setDelimiter(char delimiter) {
		this.delimiter = delimiter;
	}

	@Override
	protected L parseObject(String text) {
		L collection = newCollection();
		int index = 0;
		while (true) {
			int endIndex = indexOf(text, index);

			// Last element?
			if (endIndex == -1) {
				collection.add(text.substring(index));
				break;
			}
			collection.add(text.substring(index, endIndex));
			index = endIndex + 1;
		}
		return collection;
	}

	private int indexOf(String text, int index) {
		int delimiterIndex = text.indexOf(delimiter, index);

		// Escaped?
		if (delimiterIndex > 0 && text.charAt(delimiterIndex - 1) == '\\') {
			return indexOf(text, delimiterIndex + 1);
		}
		return delimiterIndex;
	}

	protected abstract L newCollection();

}
